<template>
  <div>
    <Card dis-hover>
      <Form ref="queryForm">
        <Row style="margin-bottom:10px;">
          <Col span="24" style="text-align: right;">
            <Button icon="md-create"
                    style="margin-right:10px;"
                    type="primary" @click="create" :disabled="!hasPermission('Pages.Administration.Roles.Create')">新建角色
            </Button>
            <Button icon="md-search" type="success" @click="getPage">搜索</Button>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col span="12">
            <FormItem prop="filter" style="width:100%;margin-bottom:10px;">
              <Input v-model="pageRequest.filter" clearable placeholder="在角色名称、角色描述中搜索" @on-clear="handleClear"></Input>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem prop="date" style="width:100%;margin-bottom:10px;">
              <DatePicker :editable="false" format="yyyy/MM/dd" placeholder="选择创建时间范围" placement="bottom-start"
                          split-panels style="width:100%;" type="daterange"
                          @on-change="dateChange" @on-clear="handleClear" transfer></DatePicker>
            </FormItem>
          </Col>
        </Row>
        <collapse-transition>
          <Row v-if="advancedSearch">
            <Col span="24">
              <FormItem prop="permission" style="width:100%;">
                <Input ref="permissions" v-model="pageRequest.permissionsDisplay" :maxlength="1024" clearable
                       placeholder="请选择权限"
                       readonly @on-clear="handlePermissionClear" @on-focus="handlePermissionFocus">
                </Input>

              </FormItem>
            </Col>
          </Row>
        </collapse-transition>
        <Row>
          <Col span="24">
            <Button v-show="advancedSearch" icon="ios-arrow-up" type="text"
                    @click="toggleClick">隐藏高级搜索
            </Button>
            <Button v-show="!advancedSearch" icon="ios-arrow-down" type="text"
                    @click="toggleClick">显示高级搜索
            </Button>
          </Col>
        </Row>
      </Form>

      <Table :columns="columns" :data="list" :loading="loading" border class="margin-top-10"
             no-data-text="没有任何数据" no-filtered-data-text="没有任何数据" @on-sort-change="sortingChange">
        <template slot="actions" slot-scope="{row}">
          <Dropdown placement="bottom-end" transfer @on-click="handleClickActionDropdown">
            <Button size="small" type="primary">
              操作
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem :name="JSON.stringify({row:row,name:'update',})"
                            :disabled="!hasPermission('Pages.Administration.Roles.Update')">更新
              </DropdownItem>
              <template v-if="row.isStatic">
                <DropdownItem disabled>删除</DropdownItem>
              </template>
              <template v-else>
                <DropdownItem :name="JSON.stringify({row:row,name:'remove'})"
                              :disabled="!hasPermission('Pages.Administration.Roles.Delete')">删除
                </DropdownItem>
              </template>
            </DropdownMenu>
          </Dropdown>
        </template>
      </Table>
      <Page :current="currentPage" :page-size="pageSize" :page-size-opts="[10,20,30,40]" :total="totalCount"
            class="margin-top-10"
            show-sizer show-total @on-change="pageChange"
            @on-page-size-change="pageSizeChange">
      </Page>
    </Card>
    <role-modal v-if="roleModalMount" v-model="roleModalShow" :modal-data="roleData"
                @save-success="getPage"></role-modal>
    <permission-modal v-if="permissionModalMountForSearch" v-model="permissionModalShowForSearch"
                      :modal-data="permissionDataForSearch"
                      @on-save="handlePermissionConfirmForSearch"></permission-modal>
  </div>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import RoleModal from '@/views/administration/role/modal/role-modal.vue';
import PermissionModal from '@/views/administration/role/modal/permission-modal.vue';
import PageRequest from '@/store/entities/page-request';
import Util from '@/lib/util';
import CollapseTransition from '@/components/common/collapse-transition';
import RoleExpand from '@/components/expand/role-expand.vue';

class PageRoleRequest extends PageRequest {
  filter: string = '';
  sorting: string = '';
  permissions: string[] = [];
  permissionsDisplay: string;
  startTime: string = '1900-01-01 00:00:00';
  endTime: string = '2099-12-31 23:59:59';
  isStatic: any[] = [];
  isDefault: any[] = [];
}

@Component({
  components: {
    CollapseTransition,
    RoleModal,
    PermissionModal,
    RoleExpand,
  },
})
export default class Role extends AbpBase {
  name: string = 'Role';


  advancedSearch: boolean = false;
  pageRequest: PageRoleRequest = new PageRoleRequest();

  roleModalMount: boolean = false;
  roleModalShow: boolean = false;
  roleData: any;

  permissionModalMountForSearch: boolean = false;
  permissionModalShowForSearch: boolean = false;
  permissionDataForSearch: any;

  columns = [
    {
      type: 'expand',
      width: 30,
      render: (h: any, params: any) => {
        return h(RoleExpand, {
          props: {
            row: params.row,
          },
        }, []);
      },
    },
    {
      title: '角色名',
      key: 'displayName',
      width: 180,
      align: 'center',
      sortable: this.$config.sorting.administration.role,
      ellipsis: true,
      tooltipTheme: 'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '系统',
      key: 'isStatic',
      width: 100,
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.isStatic) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.success,
              type: 'pandx fa fa-flag',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.disabled,
              type: 'pandx fa fa-flag',
            },
          }, [])
        }
      },
      filters: [
        {
          label: '是',
          value: true,
        }, {
          label: '否',
          value: false,
        },
      ],
      filterRemote: (array) => {
        this.pageRequest.isStatic = array;
        this.getPage();
      },
      ellipsis: true,
      tooltipTheme: 'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '默认',
      key: 'isDefault',
      width: 100,
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.isDefault) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.success,
              type: 'pandx fa fa-flag',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.disabled,
              type: 'pandx fa fa-flag',
            },
          }, [])
        }
      },
      filters: [
        {
          label: '是',
          value: true,
        }, {
          label: '否',
          value: false,
        },
      ],
      filterRemote: (array) => {
        this.pageRequest.isDefault = array;
        this.getPage();
      },
      ellipsis: true,
      tooltipTheme: 'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '角色描述',
      key: 'description',
      align: 'center',
      minWidth: 240,
      ellipsis: true,
      tooltipTheme: 'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '创建时间',
      key: 'creationTime',
      align: 'center',
      width: 180,
      sortable: this.$config.sorting.administration.role,
      render: (h: any, params: any) => {
        return h('span', {}, Util.getTime(params.row.creationTime));
      },
      ellipsis: true,
      tooltipTheme: 'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '操作',
      width: 110,
      slot: 'actions',
      align: 'center',
    },
  ];


  get list() {
    return this.$store.state.role.list;
  }

  get loading() {
    return this.$store.state.role.loading;
  }

  get pageSize() {
    return this.$store.state.role.pageSize;
  }

  get totalCount() {
    return this.$store.state.role.totalCount;
  }

  get currentPage() {
    return this.$store.state.role.currentPage;
  }


  dateChange(date: any[]) {
    this.pageRequest.startTime = (date[0] === '' ? '1900-01-01' : date[0]) + ' 00:00:00';
    this.pageRequest.endTime = (date[1] === '' ? '2099-12-31' : date[1]) + ' 23:59:59';

  }

  async create() {
    await this.$store.dispatch({
      type: 'permission/getAllPermissions',
    });
    this.roleData = {data: null, update: false};
    this.roleModalMount = true;
    this.$nextTick(() => {
      this.roleModalShow = true;
    });
  }

  toggleClick() {
    this.advancedSearch = !this.advancedSearch;
  }

  async handleClickActionDropdown(name: string) {
    const temp: any = JSON.parse(name);
    switch (temp.name) {
      case 'update':
        await this.update(temp.row);
        break;
      case 'remove':
        await this.remove(temp.row);
        break;
    }
  }

  async pageChange(page: number) {
    this.$store.commit('role/setCurrentPage', page);
    await this.getPage();
  }

  async pageSizeChange(pageSize: number) {
    this.$store.commit('role/setPageSize', pageSize);
    await this.getPage();
  }

  async sortingChange(sorting: any) {
    if (sorting.column.sortable === 'custom') {
      if (sorting.order === 'asc' || sorting.order === 'desc') {
        this.pageRequest.sorting = sorting.key + ' ' + sorting.order;
      }
      await this.getPage();
    }
  }

  async getPage() {
    this.pageRequest.maxResultCount = this.pageSize;
    this.pageRequest.skipCount = (this.currentPage - 1) * this.pageSize;
    await this.$store.dispatch({
      type: 'role/obtainRoles',
      data: this.pageRequest,
    });
  }

  async update(row: any) {
    await this.$store.dispatch({
      type: 'permission/getAllPermissions',
    });
    await this.$store.dispatch({
      type: 'role/getRoleForEdit',
      data: row,
    });
    this.roleData = {data: row, update: true};
    this.roleModalMount = true;
    this.$nextTick(() => {
      this.roleModalShow = true;
    });
  }

  handleClear() {
    this.getPage();
  }

  async remove(row: any) {
    this.$M.confirm({
      title: '系统提示',
      content: '确定要删除角色 ' + row.displayName + ' 吗？',
      onOk: async () => {
        await this.$store.dispatch({
          type: 'role/deleteRole',
          data: row,
        });
        this.$Message.success({
          background: true,
          content: '角色 ' + row.displayName + ' 已删除成功',
          duration: this.$config.duration,
        });
        await this.getPage();
      },
      onCancel: () => {
      },
    });
  }

  async handlePermissionFocus() {
    await this.$store.dispatch({
      type: 'permission/getAllPermissions',
    });
    this.permissionDataForSearch = {role: null, selectedNodes: this.pageRequest.permissions};
    this.permissionModalMountForSearch = true;
    this.$nextTick(() => {
      this.permissionModalShowForSearch = true;
    });
  }

  handlePermissionConfirmForSearch(selectedNodes: any, role: any) {
    this.pageRequest.permissionsDisplay = '选择了 ' + selectedNodes.length + ' 个权限';
    this.pageRequest.permissions = selectedNodes.map(item => {
      return item.name;
    });
  }

  handlePermissionClear() {
    this.pageRequest.permissions = [];
    this.getPage();
  }


  async created() {
    await this.getPage();
  }
}
</script>

<style scoped lang="less">

</style>
